import { OPERATION_ICONS } from './conf.js';

import { date } from '@teld/q-components';

export const useOperationProps = {
  dataType: String,
  operation: {
    type: Object,
    default() {
      return {
        name: 'default',
        // text: OPERATION_DESCRIPTORS_LANG.default,
        icon: OPERATION_ICONS.default,
        filterValue: void 0,
      };
    },
  },
};

function isValidDate(value) {
  return (
    // false === value instanceof Date &&
    // typeof value === 'string' &&
    date.isValid(value)
  );
}

function isSameDate(value, filterValue, onlyDate) {
  return onlyDate
    ? date.isSameDate(value, filterValue, 'year') &&
        date.isSameDate(value, filterValue, 'month') &&
        date.isSameDate(value, filterValue, 'day')
    : date.isSameDate(value, filterValue);
}
function extractDate(str, mask, dateLocale) {
  if (mask) {
    return date.extractDate(str, mask, dateLocale);
  } else {
    return new Date(Date.parse(str));
  }
}
export const filterRowWithDate = (value, filter) => {
  let dataType = filter.dataType?.toLowerCase();
  //'=', '<>', '<', '<=', '>', '>=', 'between'

  if (isValidDate(value)) {
    value = extractDate(value);
  } else {
    return false;
  }
  let filterValue;
  let onlyDate = 'date' == dataType;
  if ('between' == filter.name) {
    let dateFrom = filter.filterValue[0];
    let dateTo = filter.filterValue[filter.filterValue.length - 1];
    let returnValue = false;
    if (dateFrom && isValidDate(dateFrom)) {
      dateFrom = extractDate(dateFrom);
      returnValue = value >= dateFrom;
    }
    if (returnValue && dateTo && isValidDate(dateTo)) {
      dateTo = extractDate(dateTo);
      returnValue = value <= dateTo;
    }
    return returnValue;
  } else {
    if (isValidDate(filter.filterValue)) {
      filterValue = extractDate(filter.filterValue);
      switch (filter.name) {
        default:
        case '=':
          return isSameDate(value, filterValue, onlyDate);
          break;
        case '<>':
          return false == isSameDate(value, filterValue, onlyDate);
          break;
        case '<':
          return value < filterValue;
          break;
        case '<=':
          return value <= filterValue;
          break;
        case '>':
          return value > filterValue;
          break;
        case '>=':
          return value >= filterValue;
          break;
      }
    } else {
      return false;
    }
  }
};
